import { useState, useRef, useEffect } from 'react'
import './App.css'

type User = {
  name: string
  age: number
}

type Props = {
  onGetMsg?: (msg: string) => void
}

function Son(props: Props) {
  const { onGetMsg } = props
  const clickHandler = () => {
    onGetMsg && onGetMsg('hello')
  }
  return <button onClick={clickHandler}>senMsg</button>
}

/**
 * 
 * @returns 根据初始值自动推断
 */

function App() {
  const [value, toggle] = useState(false)

  const changeValue = () => {
    toggle(!value)
  }

  // const [user, setUser] = useState<User | null>(null) // 初始值为User或null
  // const [user, setUser] = useState<User>({
  //   name: 'MasterH',
  //   age: 18
  // }) // 对象
  const [user, setUser] = useState<User>(() => {
    return {
      name: 'MasterH',
      age: 18
    }
  }) // 函数，返回对象

  const changeUser = () => {
    setUser({
      name: 'MasterH2',
      age: 20
    })
  }

  const getMsgHandle = (msg: string) => {
    console.log(msg)
  }

  const domRef = useRef<HTMLInputElement>(null)
  useEffect(() => {
    domRef.current?.focus() // 防止出现null，可选链
  })

  const timeRef = useRef<number | undefined>(undefined)
  useEffect(() => {
    domRef.current?.focus()
    timeRef.current = setInterval(() => {
      console.log('hello')
    }, 1000)

    return () => clearInterval(timeRef.current)
  }, [])
  return (
    <>
      <div>
        this is app {value ? 'true' : 'false'}
        <button onClick={changeValue}>改变value</button>

        <br />

        <div>name: {user?.name}, age: {user?.age}</div>
        <button onClick={changeUser}>改变user数据</button>

        <br />

        <Son onGetMsg={(msg) => console.log(msg)} />
        <Son onGetMsg={getMsgHandle} />

        <input ref={domRef} />
      </div>
    </>
  )
}

export default App
